package controllers

import (
	"e-shops/models"
	beego "github.com/beego/beego/v2/server/web"
)

type GoodsController struct {
	beego.Controller
}

func (c *GoodsController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	s, _ := c.GetInt("shop")
	p, _ := c.GetFloat("price")
	g := models.Good{
		Name:    c.GetString("name"),
		ShopsId: s,
		Price:   p,
		Data:    c.GetString("data"),
	}
	err := models.DB.Create(&g).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "服务器：zzz...",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "我来到，我看见，我记录",
	}
	c.ServeJSON()
}
func (c *GoodsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var gs []models.Good
	s, _ := c.GetInt("shop")
	err := models.DB.Where("shops_id = ?", s).Find(&gs)
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "服务器：zzz...",
		}
		c.ServeJSON()
		return
	}
	var Gs []struct {
		g      models.Good
		Images []models.GImage
	}
	for _, g := range gs {
		var images []models.GImage
		models.DB.Where("form_id = ?", g.ID).Find(&images)
		Gs = append(Gs, struct {
			g      models.Good
			Images []models.GImage
		}{g: g, Images: images})
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "商品名录如下所呈",
		Data: Gs,
	}
	c.ServeJSON()
}
func (c *GoodsController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Good{}, id).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "服务器：zzz...",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "删除成功",
	}
	c.ServeJSON()
}
func (c *GoodsController) ImgAdd() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	id, _ := c.GetInt("id")
	var image models.GImage
	image.Image = models.GetImage(c.GetFile("image"))
	image.FromId = id
	err := models.DB.Create(&image).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "服务器：zzz...",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "图片成功",
	}
	c.ServeJSON()
}
